/**
 * Created by John on 2016/7/15.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();
var myDB = null;

mongo.connect('mongodb://localhost/', function (err, db) {
    myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        console.log('Before Updating:');
        showDocs(collection, updateDoc);
    });
});

function showDocs(collection, callback) {
    var query = {word: {$in: ['say', 'says']}};
    collection.find(query, function (err, items) {
        items.toArray(function (err, items) {
            for (var i = 0; i < items.length; i++) {
                console.log(items[i]);
            }
            callback(collection);
        });
    });
}

function updateDoc(collection) {
    var query = {word: 'say'};
    var update = {
        $set: {word: 'says'},
        $inc: {size: 1, 'stats.consonants': 1}
    };

    var options = {w: 1, wtimeout: 5 * 1000, journal: true, fsync: false, upsert: false, multi: false};

    collection.update(query, update, options, function (err, items) {
        console.log();
        console.log('Updating Doc Results:');
        console.log(items ? items.result : items);
        console.log();
        console.log('After Updating Doc:');
        showDocs(collection, resetDoc);
    })
}

function resetDoc(collection) {
    var query = {word: 'says'};
    var update = {
        $set: {word: 'say'},
        $inc: {size: -1, 'stats.consonants': -1}
    };

    var options = {w: 1, wtimeout: 5 * 1000, journal: true, fsync: false, upsert: false, multi: false};

    collection.update(query, update, options, function (err, items) {
        console.log();
        console.log('Reset Doc Results:');
        console.log(items ? items.result : items);
        console.log();
        console.log('After Resetting Doc:');
        showDocs(collection, close);
    })
}

function close() {
    setTimeout(function () {
        myDB.close();
    }, 3000);
}